package com.jty.lib_base.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.Nullable;

import com.jty.lib_base.utils.DensityUtils;
import com.jty.lib_base.utils.DrawHelper;
import com.jty.lib_base.utils.MathHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 南丁格尔玫瑰图
 */
public class LsspRoseLeafView extends View{
    private static final String MAIN_COLOR ="#FFDDDDDD" ;
    private static final float SPANNED = DensityUtils.dpToPx(60);
    //绘制的画笔
    Paint mPaint;
    //外圈
    private Paint mOutPaint;

    //玫瑰花瓣的颜色
    private String[] colors = {
            "#FF179BDF", "#FFFF713B", "#FFFF4040", "#FFFF713B",
            "#FFBC1CBA", "#FF42CECE", "#FFFF99C3", "#FF4A5DC9",
            "#FF179BDF", "#FF7E8299", "#FF1CBC9C", "#FF008000"
    };

    //需要减少半径集合
    //绘制扇形的宽度
    private float width;
    //绘制扇形的高度
    private float height;
    //起始点
    private float start;
    //绘制的起始角度          绘制时候是逆时针
    private int startSweepAngle= 270;
    //图形的中心点
    private int centerX;
    private int centerY;
    //花瓣份额比例
    private List<Float> values = new ArrayList<>();
    //需要减少的半径
    private List<Float> radius = new ArrayList<>();
    //绘制的文字
    private List<String> markers = new ArrayList<>();

    private boolean isMoving=false;

    private float maxRadius = 0f;

    private float mPercent = 0.0f;

    private List<LsspRoseLeafView.PieceDataHolder> pieceDataHolders = new ArrayList<>();

    public LsspRoseLeafView(Context context) {
        this(context,null);
    }

    public LsspRoseLeafView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LsspRoseLeafView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(Math.min(widthMeasureSpec,heightMeasureSpec),
                Math.min(widthMeasureSpec,heightMeasureSpec));
    }

    private void init() {
        //初始化画笔相关参数
        mPaint=new Paint();
        mPaint.setColor(Color.parseColor(MAIN_COLOR));
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setTextSize(DensityUtils.dpToPx(14));
        mPaint.setStrokeWidth(DensityUtils.dpToPx(0.5f));
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);

        mOutPaint=new Paint();
        mOutPaint.setColor(Color.parseColor(MAIN_COLOR));
        mOutPaint.setAntiAlias(true);
        mOutPaint.setDither(true);
        mOutPaint.setStrokeWidth(DensityUtils.dpToPx(1f));
        mOutPaint.setStyle(Paint.Style.STROKE);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        centerX =( getRight() - getLeft() )/2;//中点
        centerY = ( getBottom() - getTop()) /2;

        start=DensityUtils.dpToPx(50);
        width=getWidth()-start;
        height=getHeight()-start;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //绘制面板白色
        canvas.drawColor(Color.WHITE);
        //绘制文本内容
        drawRoseContent(canvas);
        //绘制玫瑰花瓣
        drawRoseLeafCenter(canvas);

    }


    /**
     * 处理特殊的颜色获取
     * @param color
     * @return
     */
    private int getSpecialColor(String color){
        return isMoving?Color.WHITE:Color.parseColor(color);
    }


    /**
     * 绘制玫瑰文本内容
     * @param canvas
     */
    protected void drawRoseContent(Canvas canvas) {
        if (markers.size()>0 && values.size() > 0){
            if(isMoving)mPaint.setColor(Color.WHITE);
            else mPaint.setColor(Color.GRAY);
            float sumValue = 0f;
            for (int i = 0; i < markers.size();i++){
                renderLabelLine(markers.get(i),mPercent,centerX ,centerY,maxRadius,
                        MathHelper.getInstance().add(-sumValue+startSweepAngle,-mPercent/2),canvas,mPaint, false);
                sumValue += mPercent;
            }
        }
    }

    /**
     * 绘制玫瑰花瓣
     * 记录下规律
     *一共是360
     * 份额越大
     * 半径越大
     * 颜色越深
     * @param canvas
     */
    protected void drawRoseLeafCenter(Canvas canvas) {

        if (pieceDataHolders.size()==0)return;
        float span = maxRadius / 3;
        for (int i = 0; i < 4; i++){
            canvas.drawCircle(centerX,centerY, maxRadius - DensityUtils.dpToPx(20) - span * i,mOutPaint);
        }
        float sum = 0f;
        float percent = (float)360 / pieceDataHolders.size();
        for (int i = 0; i < pieceDataHolders.size();i++){
            mPaint.setColor(Color.parseColor(colors[i]));
            canvas.drawArc(new RectF(centerX - radius.get(i),centerY-radius.get(i),centerX+radius.get(i),centerY+radius.get(i)),
                 -sum + (startSweepAngle - percent),percent,true,mPaint);
            sum+=percent;
        }
    }

    /**
     * 绘制折线label
     * @param text
     * @param cirX
     * @param cirY
     * @param radius
     * @param calcAngle
     * @param canvas
     * @param paintLabel
     * @param isRotate
     * @return
     */
    private PointF renderLabelLine(String text, float itemAngle,
                                   float cirX, float cirY, float radius, float calcAngle,
                                   Canvas canvas, Paint paintLabel, boolean isRotate)
    {

        float pointRadius = 0.0f;
        //显示在扇形的外部
        //1/4处为起始点
        float calcRadius = MathHelper.getInstance().sub(radius  , radius / 3.f);
        MathHelper.getInstance().calcArcEndPointXY(
                cirX, cirY, calcRadius, calcAngle);

        float startX = MathHelper.getInstance().getPosX();
        float startY = MathHelper.getInstance().getPosY();

        //延长原来半径的一半在外面
        calcRadius = radius / 3f + DensityUtils.dpToPx(5);
        MathHelper.getInstance().calcArcEndPointXY(startX, startY, calcRadius, calcAngle);
        float stopX = MathHelper.getInstance().getPosX();
        float stopY = MathHelper.getInstance().getPosY();



        float endX = 0.0f,endLabelX = 0.0f;
        if(Float.compare(stopX, cirX) == 0){ //位于中间竖线上
            if(Float.compare(stopY, cirY) == 1 ) //中点上方,左折线
            {
                paintLabel.setTextAlign(Paint.Align.LEFT);
                endX = stopX; //+ pointRadius;
                endLabelX = endX + pointRadius;
            }else{ //中点下方,右折线
                paintLabel.setTextAlign(Paint.Align.RIGHT);
                endX = stopX;
                endLabelX = endX - pointRadius;
            }
        }else if(Float.compare(stopY, cirY) == 0 ){ //中线横向两端
            endX = stopX;
            if(Float.compare(stopX, cirX) == 0 ||
                    Float.compare(stopX, cirX) == -1) //左边
            {
                paintLabel.setTextAlign(Paint.Align.RIGHT);
                endLabelX = endX - pointRadius;
            }else{
                paintLabel.setTextAlign(Paint.Align.LEFT);
                endLabelX = endX + pointRadius;
            }

        }else if(Float.compare(stopX, cirX) == 1 ) //右边
        {
            paintLabel.setTextAlign(Paint.Align.LEFT);
            endX = stopX;
            endLabelX = endX + pointRadius;
        }else if(Float.compare(stopX,cirX) == -1  ) //左边
        {
            paintLabel.setTextAlign(Paint.Align.RIGHT);
            endX = stopX ;
            endLabelX = endX - pointRadius;
        }else {
            endLabelX = endX = stopX;
            paintLabel.setTextAlign(Paint.Align.CENTER);
        }

        //转折线
//        drawBrokenLine(startX,startY,stopX, stopY, endX,canvas);

        DrawHelper.getInstance().drawRotateText(text,endLabelX, stopY, itemAngle,
                canvas, paintLabel,isRotate);

        return (new PointF(endLabelX, stopY));
    }

    private void drawBrokenLine(float startX,float startY,
                                float stopX,float stopY,float endX,
                                Canvas canvas)
    {
        //连接线
        canvas.drawLine(centerX, centerY,stopX, stopY, mPaint);

        //转折线
        canvas.drawLine(stopX, stopY, endX, stopY, mPaint);
    }


    /**
     * 设置饼状图要显示的数据
     *
     * @param data 列表数据
     */
    public void setData(List<LsspRoseLeafView.PieceDataHolder> data) {

        if (data != null && data.size() > 0) {
            pieceDataHolders.clear();
            pieceDataHolders.addAll(data);
            values.clear();
            markers.clear();
            radius.clear();

            mPercent = (float)360 / pieceDataHolders.size();
            maxRadius = (int) Math.min(width,height) / 2 ;
            float maxValue = 0f;
            for (PieceDataHolder holder : data){
                maxValue = Math.max(maxValue,holder.getValue());
            }


            for (int i = 0 ; i < data.size();i++){
                values.add(data.get(i).getValue());
                markers.add(data.get(i).getMarker());
                radius.add(values.get(i) == 0.0f ? values.get(i):values.get(i) * 1.0f / maxValue * maxRadius);
            }


        }
        invalidate();
    }


    /**
     * 玫瑰花瓣每块的信息持有者
     */
    public static final class PieceDataHolder {

        /**
         * 每块扇形的值的大小
         */
        private float value;

        /**
         * 扇形的颜色
         */
        private int color;

        /**
         * 每块的标记
         */
        private String marker;


        public PieceDataHolder(float value, int color, String marker) {
            this.value = value;
            this.color = color;
            this.marker = marker;
        }

        public float getValue() {
            return value;
        }

        public void setValue(float value) {
            this.value = value;
        }

        public int getColor() {
            return color;
        }

        public void setColor(int color) {
            this.color = color;
        }

        public String getMarker() {
            return marker;
        }

        public void setMarker(String marker) {
            this.marker = marker;
        }
    }

}
